import * as d3 from "d3";
import { flameGraphList } from "@/api/topoNodeDetail";
import { flamegraph } from "d3-flame-graph";
import { computed, h, onUnmounted, ref, toRaw } from "vue";
import { flameGraphTip, genTipHtml } from "./FlameGraphTip";

export default function useFlameGraphTable({ wrapperRef,tableRef }) {
  const loading = ref(false);
  const tableData = ref([]);
  const expandedKeys = ref([]);
  const graphWrapperHeight = ref(200);
  const columns = [
    {
      title: "Pod名称",
      dataIndex: "podName",
    },
    {
      title: "容器名称",
      dataIndex: "containerName",
    },
    {
      title: "PID",
      dataIndex: "pid",
    },
    // {
    //   title: '时间',
    //   dataIndex: 'timestamp'
    // }
  ];
  const worker = ref(new Worker(new URL('./worker.js', import.meta.url)));
  const getFlameGraphData = (params) => {
    loading.value = true;
    const { containerName, podName } = params;
    flameGraphList(params)
      .then((res) => {
        const data = res.data.map((item, index) => {
          const { pid, timestamp } = item[0];
          return {
            flameData: item,
            containerName,
            pid,
            podName,
            timestamp,
            index,
          };
        });
        console.log(data, "data");
        tableData.value = data;
      })
      .finally(() => {
        loading.value = false;
      });
  };
  const expandable = computed(() => {
    return {
      expandedRowKeys: expandedKeys.value,
      expandedRowRender({ index }) {
        return h('div', {id:`flame-list-item-${index}`, style:{height: `${graphWrapperHeight.value}px`}})
        // return `<div
        //       id='flame-list-item-${index}'
        //       style='height: ${graphWrapperHeight.value}px'
        //     ></div>`;
      },
    };
  });
  const onExpand = (rowKey, { flameData, index, pid }) => {
    if(expandedKeys.value.length > 0 && expandedKeys.value[0] === pid) {
      return  expandedKeys.value = [];
    }
    expandedKeys.value = [pid];
    loading.value = true;
    const chart = flamegraph()
      .width(wrapperRef.value?.clientWidth - 20 * 2)
      .cellHeight(18)
      .transitionDuration(750)
      .transitionEase(d3.easeCubic)
      .inverted(true)
      .selfValue(false);
    const tip = flameGraphTip().html(genTipHtml);
    chart.tooltip(tip);
    const maxDepth = Math.max(flameData.map((item) => item.depth));
    // console.log(maxDepth, 'maxDepth');

    graphWrapperHeight.value = maxDepth * 20;
    console.log( flameData,'flameData',worker.value);

    worker.value.postMessage(toRaw(flameData));
    worker.value.addEventListener("message", (e) => {
      console.log(e, "e");
      Promise.resolve().then(() => {
        loading.value = (false);
        d3.select(`#flame-list-item-${index}`).datum(e.data).call(chart);
      });
    });
  };
  onUnmounted(() => {
    worker.value?.terminate()
  })
  return {
    loading,
    tableData,
    columns,
    expandedKeys,
    expandable,
    onExpand,
    getFlameGraphData,
  };
}
